package cmw.com.beijingnew.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.apkfuns.logutils.LogUtils;

import cmw.com.beijingnew.activity.MainActivity;
import cmw.com.utils.UiUtil;

/**
 * 自定义一个要求父类不拦截事件的ViewPager
 *
 * Created by Administrator on 2017-05-02.
 */

public class HorizontalScrollViewPager extends ViewPager {

    float startX = 0;
    float startY = 0;

    public HorizontalScrollViewPager(Context context) {
        super(context);
    }

    public HorizontalScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Context context = getContext();
        MainActivity mainActivity = (MainActivity) context;
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN :{//手指按下
                startX = ev.getX();
                startY = ev.getY();
                //请求父层视图不要拦截当前控件的事件（当把事件传递给当前HorizontalScrollViewPager 控件时）
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            } case MotionEvent.ACTION_MOVE :{//手指滑动
                float endX = ev.getX();
                float endY = ev.getY();
                float distanceX = endX - startX;
                float distanceY = Math.abs(endY - startY);
                if(Math.abs(distanceX) > distanceY){//水平方向滑动
                    int index = getCurrentItem();
                    //当滑动到ViewPager第0个页面，并且方向是从左到右滑动时，告诉父View拦截子View事件
                    if(index == 0 && distanceX > 0){
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }else if((index == getAdapter().getCount() -1) && distanceX < 0){
                        //当滑动到ViewPager最后一个页面，并且方向是从左到右滑动时，告诉父View拦截子View事件
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }else{
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                }else{//垂直方向滑动
                    getParent().requestDisallowInterceptTouchEvent(false);
                }
                break;
            }case MotionEvent.ACTION_UP :{//松开手指
                break;
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
